<template>
  <div class="rich-editor-page">
    <div class="header-box">
      <p>专题发布</p>
    </div>
    <div class="content-box">
      <el-form
        ref="richEditorRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="rich-editor-form"
      >
        <el-form-item label="标题" prop="subjectName">
          <el-input v-model="formData.subjectName" maxlength="24" show-word-limit autocomplete="off" style="width: 400px" />
        </el-form-item>
        <el-form-item label="链接" prop="subjectLink">
          <el-input v-model="formData.subjectLink" maxlength="100" show-word-limit autocomplete="off" style="width: 400px" />
        </el-form-item>
        <el-form-item v-if="showDesc" label="描述" prop="buttonDescribe">
          <el-input v-model="formData.buttonDescribe" maxlength="80" show-word-limit type="textarea" :rows="4" autocomplete="off" style="width: 400px" />
        </el-form-item>
        <el-form-item label="图片" prop="imageId">
          <el-upload
            accept=".jpg, .jpeg, .png, .JPG, .JPEG, .PBG"
            action=""
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadImg"
          >
            <img v-if="imgURl" :src="imgURl" class="avatar" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" style="color: #F56C82">图片尺寸建议1400*178（或长宽比8:1）</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button v-permission="'bannerRelease:submit'" type="primary" style="width: 100px" @click="onSubmit()">提 交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { uploadImg } from '@/api/submit';
import { compressImage } from '@/utils/compregressImg';
import { bannerRelease } from '@/api/banner'
import store from '@/store';
export default {
  name: 'BannerRelease',
  data() {
    const checkUrl = (rule, value, cb) => {
      const regUrl = /^(http?|https|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
      if (regUrl.test(value)) {
        return cb()
      }
      cb(new Error('请输入完整的链接（包含http://或https://）'))
    }
    return {
      formData: {},
      formRules: {
        subjectName: [
          {
            required: true, message: '标题不能为空', trigger: 'blur'
          }
        ],
        subjectLink: [
          {
            required: true, message: '链接不能为空', trigger: 'blur'
          },
          {
            validator: checkUrl,
            trigger: 'blur'
          }
        ],
        buttonDescribe: [
          {
            required: true, message: '描述不能为空', trigger: 'blur'
          }
        ],
        imageId: [
          {
            required: true, message: '请上传图片'
          }
        ]
      },
      imgURl: '',
      showDesc: true
    }
  },
  beforeDestroy() {
    store.commit('banner/setBannerInfo', null);
  },
  mounted() {
    if (store && store.state.banner.banner_info) {
      const bannerData = JSON.parse(JSON.stringify(store.state.banner.banner_info));
      this.formData = bannerData;
      if (bannerData.url) {
        // this.imgURl = process.env.VUE_APP_BASE_API + '/api/' + contentData.url;
        this.imgURl = window.location.origin + '/api/' + bannerData.url;
      }
    }
  },
  methods: {
    onSubmit() {
      this.$refs['richEditorRef'].validate(res => {
        if (res) {
          const requestBody = {
            ...this.formData
          }
          if (this.formData.id) {
            requestBody.id = this.formData.id;
          }
          bannerRelease(requestBody).then(res => {
            if (res.code === 200) {
              this.$message.success('提交成功');
              this.imgURl = '';
              this.formData = {};
              this.$refs['richEditorRef'].resetFields();
              this.$router.push({ path: '/bannerAudit' });
            }
          })
        }
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpg';
      const isPng = file.type === 'image/png';
      const isJpeg = file.type === 'image/jpeg';
      // 1MB=1024*1024(1MB=1024KB 1KB=1024MB)
      const is1M = file.size / 1024 / 1024 < 20;
      // 限制文件上传类型
      if (!isJPG && !isPng && !isJpeg) {
        this.$message.error('上传图片只能是 png,jpg,jpeg 格式!');
        return false
      }

      // 限制文件上传大小
      if (!is1M) {
        this.$message.error('上传图片大小不能超过 20MB!');
        return false
      }
      this.formData.imageId = URL.createObjectURL(file);
      return true
    },
    uploadImg(file) {
      const formData = new FormData();
      formData.append('file', file.file);
      uploadImg(formData).then(res => {
        if (res.code === 200) {
          this.$message.success('图片上传成功');
          compressImage(file.file).then(data => {
            console.log(111111, data);
            const formData1 = new FormData();
            formData1.append('file', data.compressFile);
            formData1.append('materialId', res.data.materialId)
            this.imgURl = window.location.origin + '/api/' + res.data.url;
            this.formData.imageId = res.data.materialId;
            this.$nextTick(() => {
              this.$refs['richEditorRef'].clearValidate('imageId');
            });
          });
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.rich-editor-page {
  width: 100%;
  height: 100%;

  .header-box {
    width: 100%;
    height: 80px;
    line-height: 80px;
    background-color: #fff;

    p {
      margin-left: 30px;
      font-size: 28px;
      font-weight: 500;
      font-family: PingFangSC-Medium, PingFang SC;
    }
  }

  .content-box {
    overflow-y: auto;
    background-color: #fff;
    margin-top: 10px;
    width: 100%;
    height: calc(100% - 90px);
    padding: 30px;
    box-sizing: border-box;

    ::v-deep .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    ::v-deep .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }

    ::v-deep .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    ::v-deep .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>

<style scoped>
.rich-editor-form::v-deep .el-textarea__inner {
  resize: none;
}
</style>
